//
//  ComposeViewController.swift
//  WBDemo
//
//  Created by Meng on 17/2/27.
//  Copyright © 2017年 demo. All rights reserved.
//

import UIKit
import SVProgressHUD

class ComposeViewController: UIViewController, UITextViewDelegate {

    @IBOutlet weak var sendItem: UIBarButtonItem!
    
    @IBOutlet weak var textView: TextView!
    
    @IBOutlet weak var toolBarBottomCons: NSLayoutConstraint!
    
    @IBOutlet weak var tipLabel: UILabel!
    
    @IBOutlet weak var containerViewHeightCons: NSLayoutConstraint!
    
    var photoPickerViewController: PhotoPickerViewController?
    
    let maxCount = 140
    
    private lazy var titleView: TitleView = {
        let tv = TitleView()
        tv.frame = CGRect(x: 0, y: 0, width: 200, height: 44)
        return tv
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        navigationItem.titleView = titleView
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardChange(notice:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        // 将键盘控制器, 添加为当前控制器的子控件
        addChildViewController(keyboardEmoticonVC)
        containerViewHeightCons.constant = 0
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if containerViewHeightCons.constant == 0 {
            textView.becomeFirstResponder()
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        textView.resignFirstResponder()
    }
    
    @IBAction func choseAction() {
        dismiss(animated: true, completion: nil)
    }
    
    @IBAction func showPhotoView(_ sender: Any) {
        containerViewHeightCons.constant = view.frame.height * 0.7
        UIView.animate(withDuration: 0.25) { 
            self.view.layoutIfNeeded()
        }
        textView.resignFirstResponder()
    }
    
    @IBAction func emoticonAction(_ sender: Any) {
        // 通过观察发现, 如果是系统默认的键盘inputView = nil
        // 如果不是系统自带的键盘, 那么inputView != nil
        // 注意点: 要想切换切换, 必须先关闭键盘, 切换之后再打开
        
        // 关闭键盘
        textView.resignFirstResponder()
        
        // 1.判断inputView是否是nil
        if textView.inputView != nil {
            // 切换为系统键盘
            textView.inputView = nil
        } else {
            // 切换为自定义键盘
            textView.inputView = keyboardEmoticonVC.view
        }
        
        // 重新打开键盘
        textView.becomeFirstResponder()
    }

    @IBAction func sendAction() {
        
        let image = photoPickerViewController?.images.first
        
        let str = textView.emoticonStr()
        
        SVProgressHUD.show(withStatus: "发送中...")
        NetworkTool.shareInstance.sendStatus(status: str, image: image) { (objc: Any?, error: Error?) in
            if error != nil {
                SVProgressHUD.showError(withStatus: "发送失败")
            } else {
                SVProgressHUD.showSuccess(withStatus: "发送成功")
                self.choseAction()
            }
        }
    }
    
    @objc private func keyboardChange(notice: Notification) {
        // 1.获取键盘的frame
        let rect = (notice.userInfo![UIKeyboardFrameEndUserInfoKey]! as AnyObject).cgRectValue
        // 2.获取屏幕的高度
        let height = UIScreen.main.bounds.height
        // 3.计算需要移动的距离
        let offsetY = height - rect!.origin.y
        // 获取动画当前节奏, 如果节奏是7, 连续执行两次动画会直接忽略上一下进入下一次
        // 而普通节奏会等待上一次做完才会执行下一次
        let curve = notice.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber
        // 4.修改底部工具条约束
        toolBarBottomCons.constant = offsetY
        UIView.animate(withDuration: 0.25, animations: {
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve.intValue)!)
            self.view.layoutIfNeeded()
        })
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "photoPicker" {
            photoPickerViewController = segue.destination as? PhotoPickerViewController
        }
    }
    
    // MARK: - UITextViewDelegate
    func textViewDidChange(_ textView: UITextView) {
        sendItem.isEnabled = textView.hasText
        self.textView.textChange()
        let count = textView.text.characters.count
        let leftCount = maxCount - count
        tipLabel.text = "\(leftCount)"
        sendItem.isEnabled = leftCount >= 0
        tipLabel.textColor = leftCount >= 0 ? UIColor.lightGray : UIColor.red
    }
    
    // MARK: - 懒加载
    /// 表情键盘控制器
    private lazy var keyboardEmoticonVC: XMGKeyboardEmoticonViewController = XMGKeyboardEmoticonViewController {[unowned self] (emoticon: XMGKeyboardEmoticon) in
        self.textView.insertEmoticon(emoticon: emoticon)
        self.textViewDidChange(self.textView)
    }
    
    deinit {
        
        NotificationCenter.default.removeObserver(self)
    }
}
